{% extends "admin/layout.html" %}

{% block title %}资产管理 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
    <div class="container-fluid">
        <!-- 页面标题和操作按钮 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">资产管理</h1>
                <nav aria-label="breadcrumb">

                </nav>
            </div>
            <div class="btn-group">
                <a href="{{ url_for('asset.asset_form') }}" class="btn btn-primary">
                    <i class="fas fa-plus me-1"></i> 新增资产
                </a>
                <a href="{{ url_for('asset.import_assets') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-upload me-1"></i> 导入
                </a>
                <a href="{{ url_for('asset.export_assets') }}" class="btn btn-outline-success">
                    <i class="fas fa-download me-1"></i> 导出
                </a>
            </div>
        </div>

        <!-- 统计卡片 -->
        <!-- 替换统计卡片部分 -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stat-card border-left-primary h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">总资产数量</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.total_assets|default(0) }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-laptop fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stat-card border-left-success h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">资产总价值</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">¥{{ "%.2f"|format(stats.total_value|default(0)) }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stat-card border-left-warning h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">即将过保</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.expiring_soon|default(0) }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card stat-card border-left-info h-100">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">需维护</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ stats.need_maintenance|default(0) }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-tools fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-4">
                        <label for="keyword" class="form-label">关键词</label>
                        <input type="text" class="form-control" id="keyword" name="keyword"
                               value="{{ filters.keyword }}" placeholder="资产名称/编号/序列号">
                    </div>
                    <div class="col-md-2">
                        <label for="category_id" class="form-label">资产类别</label>
                        <select class="form-select" id="category_id" name="category_id">
                            <option value="">全部类别</option>
                            {% for category in categories %}
                                <option value="{{ category.id }}" {% if filters.category_id == category.id %}selected{% endif %}>
                                    {{ category.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="confirmation_status" class="form-label">确认状态</label>
                        <select class="form-select" id="confirmation_status" name="confirmation_status">
                            <option value="">全部状态</option>
                            <option value="pending" {% if filters.confirmation_status == 'pending' %}selected{% endif %}>待确认</option>
                            <option value="confirmed" {% if filters.confirmation_status == 'confirmed' %}selected{% endif %}>已确认</option>
                            <option value="rejected" {% if filters.confirmation_status == 'rejected' %}selected{% endif %}>已拒绝</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="status" class="form-label">状态</label>
                        <select class="form-select" id="status" name="status">
                            <option value="">全部状态</option>
                            <option value="available" {% if filters.status == 'available' %}selected{% endif %}>可用</option>
                            <option value="in_use" {% if filters.status == 'in_use' %}selected{% endif %}>使用中</option>
                            <option value="maintenance" {% if filters.status == 'maintenance' %}selected{% endif %}>维护中</option>
                            <option value="retired" {% if filters.status == 'retired' %}selected{% endif %}>已报废</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label for="assigned_to_id" class="form-label">使用人</label>
                        <select class="form-select" id="assigned_to_id" name="assigned_to_id">
                            <option value="">全部人员</option>
                            {% for member in members %}
                                <option value="{{ member.id }}" {% if filters.assigned_to_id == member.id %}selected{% endif %}>
                                    {{ member.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-search me-1"></i> 搜索
                        </button>
                        <a href="{{ url_for('asset.asset_list') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-refresh me-1"></i> 重置
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- 资产列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">资产清单</h5>
                <div class="text-muted">
                    共 {{ pagination.total }} 项资产
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                        <tr>
                            <th>资产编号</th>
                            <th>资产名称</th>
                            <th>类别</th>
                            <th>型号/品牌</th>
                            <th>状态</th>
                            <th>使用人</th>
                            <th>位置</th>
                            <th>当前价值</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for asset in assets %}
                            <tr data-asset-id="{{ asset.id }}">
                                <td>
                                    <strong>{{ asset.asset_number }}</strong>
                                    {% if asset.serial_number %}
                                        <br><small class="text-muted">SN: {{ asset.serial_number }}</small>
                                    {% endif %}
                                </td>
                                <td>
                                    <a href="{{ url_for('asset.asset_detail', asset_id=asset.id) }}" class="text-decoration-none">
                                        {{ asset.name }}
                                    </a>
                                </td>
                                <td>{{ asset.category.name if asset.category else '-' }}</td>
                                <td>
                                    {% if asset.model or asset.brand %}
                                        {{ asset.model or '' }} {{ asset.brand or '' }}
                                    {% else %}
                                        -
                                    {% endif %}
                                </td>
                                <td>
    <span class="badge
        {% if asset.status == 'in_use' %}bg-success
        {% elif asset.status == 'available' %}bg-primary
        {% elif asset.status == 'maintenance' %}bg-warning
        {% elif asset.status == 'retired' %}bg-secondary
        {% elif asset.status == 'draft' %}bg-light text-dark
        {% elif asset.status == 'pending' %}bg-info
        {% elif asset.status == 'lost' %}bg-danger
        {% elif asset.status == 'reserved' %}bg-purple
        {% else %}bg-light text-dark{% endif %}">
        {{ asset.status_label }}
    </span>

                                    <!-- 确认状态标识 -->
                                    {% if asset.confirmation_status == 'pending' %}
                                        <span class="badge bg-warning ms-1" title="待确认">待确认</span>
                                    {% elif asset.confirmation_status == 'rejected' %}
                                        <span class="badge bg-danger ms-1" title="已拒绝">已拒绝</span>
                                    {% endif %}

                                    <!-- 保修状态标识 -->
                                    {% if asset.warranty_status == 'expiring_soon' %}
                                        <i class="fas fa-exclamation-triangle text-warning ms-1" title="保修即将到期"></i>
                                    {% elif asset.warranty_status == 'expired' %}
                                        <i class="fas fa-times-circle text-danger ms-1" title="已过保修期"></i>
                                    {% endif %}

                                    <!-- 自动发现标识 -->
                                    {% if asset.auto_discovered %}
                                        <i class="fas fa-robot text-info ms-1" title="自动发现资产"></i>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if asset.assigned_to %}
                                        {{ asset.assigned_to.name }}
                                    {% else %}
                                        <span class="text-muted">未分配</span>
                                    {% endif %}
                                </td>
                                <td>{{ asset.location or '-' }}</td>
                                <td>
                                    {% if asset.current_value %}
                                        ¥{{ "%.2f"|format(asset.current_value) }}
                                    {% else %}
                                        -
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="{{ url_for('asset.asset_detail', asset_id=asset.id) }}"
                                           class="btn btn-outline-primary" title="查看详情">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="{{ url_for('asset.asset_form', asset_id=asset.id) }}"
                                           class="btn btn-outline-secondary" title="编辑">
                                            <i class="fas fa-edit"></i>
                                        </a>

                                        <!-- 维护记录按钮 -->
                                        <a href="{{ url_for('asset.add_maintenance_log', asset_id=asset.id) }}"
                                           class="btn btn-outline-warning" title="维护记录">
                                            <i class="fas fa-tools"></i>
                                        </a>

                                        <!-- 状态变更按钮 -->
                                        <div class="btn-group btn-group-sm"  style="position: static;">
                                            <button type="button" class="btn btn-outline-success dropdown-toggle"
                                                    data-bs-toggle="dropdown" data-bs-container="body"
                                                    data-bs-boundary="viewport" aria-expanded="false" title="变更状态">
                                                <i class="fas fa-cog"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li>
                                                    <a class="dropdown-item" href="#"
                                                       onclick="changeAssetStatus({{ asset.id }}, 'available')">
                                                        <i class="fas fa-check text-success"></i> 标记为可用
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item" href="#"
                                                       onclick="changeAssetStatus({{ asset.id }}, 'in_use')">
                                                        <i class="fas fa-user text-primary"></i> 标记为使用中
                                                    </a>
                                                </li>
                                                <li><hr class="dropdown-divider"></li>
                                                <li>
                                                    <a class="dropdown-item text-danger" href="#"
                                                       onclick="changeAssetStatus({{ asset.id }}, 'retired')">
                                                        <i class="fas fa-trash"></i> 标记报废
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="9" class="text-center py-5 text-muted">
                                    <i class="fas fa-inbox fa-3x mb-3"></i>
                                    <h5>暂无资产数据</h5>
                                    <p class="mb-3">您还没有添加任何资产，或者当前筛选条件下没有匹配的资产</p>
                                    <div class="btn-group">
                                        <a href="{{ url_for('asset.asset_form') }}" class="btn btn-primary">
                                            <i class="fas fa-plus me-1"></i> 添加第一个资产
                                        </a>
                                        <a href="{{ url_for('asset.import_assets') }}" class="btn btn-outline-secondary">
                                            <i class="fas fa-upload me-1"></i> 批量导入
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
            {% if pagination.pages > 1 %}
                <div class="card-footer">
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center mb-0">
                            {% if pagination.has_prev %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('asset.asset_list', page=pagination.prev_num, **filters) }}">上一页</a>
                                </li>
                            {% endif %}

                            {% for page_num in pagination.iter_pages() %}
                                {% if page_num %}
                                    <li class="page-item {% if page_num == pagination.page %}active{% endif %}">
                                        <a class="page-link" href="{{ url_for('asset.asset_list', page=page_num, **filters) }}">{{ page_num }}</a>
                                    </li>
                                {% else %}
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                {% endif %}
                            {% endfor %}

                            {% if pagination.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="{{ url_for('asset.asset_list', page=pagination.next_num, **filters) }}">下一页</a>
                                </li>
                            {% endif %}
                        </ul>
                    </nav>
                </div>
            {% endif %}
        </div>
    </div>

    <!-- 状态变更模态框 -->
    <div class="modal fade" id="statusModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">变更资产状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="statusForm" method="post">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newStatus" class="form-label">新状态</label>
                            <select class="form-select" id="newStatus" name="status" required>
                                <option value="available">可用</option>
                                <option value="in_use">使用中</option>
                                <option value="maintenance">维护中</option>
                                <option value="retired">已报废</option>
                                <option value="lost">丢失</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="statusNotes" class="form-label">备注</label>
                            <textarea class="form-control" id="statusNotes" name="notes" rows="3"
                                      placeholder="请输入状态变更的原因或说明..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">确认变更</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 成功提示 -->
    <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
        <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <strong class="me-auto">系统提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body"></div>
        </div>
    </div>

    <style>
        /* 修复下拉菜单被遮挡问题 */
        .table-responsive {
            position: relative;
            z-index: 1;
            overflow: visible !important;
        }

        .table td .dropdown-menu {
            position: absolute;
            z-index: 1060;
        }

        /* 确保表格行有足够的空间显示下拉菜单 */
        .table tbody tr {
            position: relative;
        }
    </style>
    <script>
    // 修复状态变更函数
    function changeAssetStatus(assetId, defaultStatus = null) {
        // 设置默认状态
        if (defaultStatus) {
            document.getElementById('newStatus').value = defaultStatus;
        }

        // 清空备注字段
        document.getElementById('statusNotes').value = '';

        const form = document.getElementById('statusForm');

        // 设置表单action
        form.action = "{{ url_for('asset.change_asset_status', asset_id=0) }}".replace('0', assetId);

        // 绑定提交事件（使用once选项确保只绑定一次）
        form.addEventListener('submit', handleStatusFormSubmit, { once: true });

        const modal = new bootstrap.Modal(document.getElementById('statusModal'));
        modal.show();
    }

    // 分离提交处理函数
    function handleStatusFormSubmit(e) {
        e.preventDefault();
        const form = e.target;

        // 收集表单数据
        const formData = new FormData(form);

        fetch(form.action, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('input[name="csrf_token"]').value,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(errData => {
                    throw new Error(errData.message || '状态更新失败');
                });
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                // 更新页面上的状态显示
                const statusBadge = document.querySelector(`tr[data-asset-id="${data.asset_id}"] .badge`);
                if (statusBadge) {
                    statusBadge.className = `badge bg-${getStatusColorClass(data.status)}`;
                    statusBadge.textContent = data.status_label;
                }

                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('statusModal'));
                if (modal) modal.hide();

                // 显示成功提示
                showToast('success', data.message || '状态已更新');

                // 刷新统计信息
                if (typeof refreshStats === 'function') {
                    refreshStats();
                }
            } else {
                showToast('error', data.message || '状态更新失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('error', error.message || '网络错误，请稍后重试');
        });
    }

    // 添加统计信息刷新函数
    function refreshStats() {
        fetch("{{ url_for('asset.api_statistics') }}")
            .then(response => response.json())
            .then(data => {
                // 更新总资产数量
                const totalAssetsEl = document.querySelector('.stat-card:nth-child(1) .font-weight-bold');
                if (totalAssetsEl) {
                    totalAssetsEl.textContent = data.total_assets || 0;
                }

                // 更新资产总价值
                const totalValueEl = document.querySelector('.stat-card:nth-child(2) .font-weight-bold');
                if (totalValueEl) {
                    totalValueEl.textContent = '¥' + (data.total_value ? data.total_value.toFixed(2) : '0.00');
                }

                // 更新即将过保
                const expiringSoonEl = document.querySelector('.stat-card:nth-child(3) .font-weight-bold');
                if (expiringSoonEl) {
                    expiringSoonEl.textContent = data.expiring_soon || 0;
                }

                // 更新需维护
                const needMaintenanceEl = document.querySelector('.stat-card:nth-child(4) .font-weight-bold');
                if (needMaintenanceEl) {
                    needMaintenanceEl.textContent = data.need_maintenance || 0;
                }
            })
            .catch(error => console.error('Error refreshing stats:', error));
    }

    // 获取状态对应的颜色类
    function getStatusColorClass(status) {
        const statusColors = {
            'in_use': 'success',
            'available': 'primary',
            'maintenance': 'warning',
            'retired': 'secondary',
            'draft': 'light',
            'pending': 'info',
            'lost': 'danger',
            'reserved': 'purple'
        };
        return statusColors[status] || 'light';
    }

    // 显示Toast的函数
    function showToast(type, message) {
        const toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            const container = document.createElement('div');
            container.className = 'toast-container position-fixed top-0 end-0 p-3';
            container.style.zIndex = '1060';
            document.body.appendChild(container);
        }

        const toastId = 'toast-' + Date.now();
        const toastHtml = `
            <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="toast-header ${type === 'success' ? 'bg-success text-white' : 'bg-danger text-white'}">
                    <strong class="me-auto">系统提示</strong>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">${message}</div>
            </div>
        `;

        document.querySelector('.toast-container').innerHTML += toastHtml;

        const toastEl = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastEl, { autohide: true, delay: 3000 });
        toast.show();

        toastEl.addEventListener('hidden.bs.toast', function() {
            toastEl.remove();
        });
    }
</script>

{% endblock %}